package net.heri.xmppchat.services;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

public class ChatServiceManager {

	private static final String TAG = ChatServiceManager.class.getSimpleName();
	private static final String SERVICE_NAME = "net.heri.xmppchat.services.chatservice";
	
	private Context mContext;
	private IChatService mService;
	private ChatServiceListener mListener;
	
	private ServiceConnection conn = new ServiceConnection() {
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mService = IChatService.Stub.asInterface(service);
			mListener.onServiceConnected();			
		}
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mService = null;
			mListener.onServiceDisconnected();			
		}	
		
	};
	
	public ChatServiceManager(Context context) {
		mContext = context;
	}
	
	public void setServiceListener(ChatServiceListener listener){
		mListener = listener;
	}
	
	public void connect(){
		// Forcely startservice		
		Intent intent = new Intent(SERVICE_NAME);
		mContext.startService(intent);
		mContext.bindService(intent, conn, Service.START_STICKY);
	}
	
	public void disconnect(){
		mContext.unbindService(conn);
	}
	
	interface ChatServiceListener {
		void onServiceConnected();
		void onServiceDisconnected();
	}
}
